package com.zingrow.web.configure.domain.service.impl;


import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jxl.Sheet;
import jxl.Workbook;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zingrow.common.utils.CommonUtils;
import com.zingrow.common.utils.PageView;
import com.zingrow.common.utils.StringUtil;
import com.zingrow.web.base.service.impl.BaseService;
import com.zingrow.web.common.utils.AnalyzeResult;
import com.zingrow.web.configure.domain.mapper.DomainMapper;
import com.zingrow.web.configure.domain.model.Domain;
import com.zingrow.web.configure.domain.service.IDomainService;
@Service
public class DomainService extends BaseService<Domain> implements IDomainService{
	@Autowired
	private DomainMapper domainMapepr;
	
	/*@Resource(name = "taskExecutor")
    private TaskExecutor taskExecutor;*/
	 @Override
	 public void initMapper() {
	     this.baseMapper = domainMapepr;
	 }
	 //模糊查询
	@Override
	public List<Domain> queryByParams(PageView pageView,String domain_domain,
			String domain_name,String domain_category,Integer is_exprot) {
		
		 Map<String, Object> map = new HashMap<String, Object>();
		 map.put("paging", pageView);
		 map.put("domain_domain", domain_domain);
		 map.put("domain_name", domain_name);
		 map.put("domain_category", domain_category);
		 map.put("is_exprot", is_exprot);
		 
		 return domainMapepr.queryByParams(map);
	 }
	 //新增
	@Override
	public boolean addDomain(Domain domain) {
		//给状态赋值为1
		if (domain.getIs_delete()==null) {
			domain.setIs_delete(1);
		}
		//导出状态默认值为0
		if (domain.getIs_exprot()==null) {
			domain.setIs_exprot(0);
		}	
		 return domainMapepr.addDomain(domain) > 0;
	 }
	//单个查询
	@Override
	public Domain queryByid(Integer domain_id) {
		Domain domain = domainMapepr.queryByid(domain_id);
		return domain;
	}
	 //修改
	@Override
	public boolean modifyDomain(Domain domain) {
		 return domainMapepr.modifyDomain(domain) > 0;
	 }
	 //删除
	@Override
	public boolean deletedomain(Integer domain_id) {
		 return domainMapepr.deletedomain(domain_id) > 0;
	 }
	//查询是否同名
	@Override
	public boolean queryByDomainAndName(Integer domain_id,String domain_domain,String domain_name) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("domain_id", domain_id);
		map.put("domain_domain", domain_domain);
		map.put("domain_name", domain_name);
		return domainMapepr.queryByDomainAndName(map)>0;
	}
	//根据名字模糊查询接口
	@Override
	public List<Domain> queryParamsByName(String domain_name) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("domain_name", domain_name);
		return domainMapepr.queryParamsByName(map);
	}
	

	//导出
	@Override
	public List<Domain> queryDomainById(List<Integer> ids) {
		List<Domain> dlist = new ArrayList<Domain>();
		dlist = domainMapepr.queryDomainById(ids);
		//修改导出状态
			if(dlist.size()>0) {
				domainMapepr.modifyDomainIsdelete(ids);
			}
		//判断
		if (dlist != null && dlist.size() > 0) {
			//把标签值id分割开查询
			for (Domain domain : dlist) {
				if ("News".equals(domain.getDomain_category())) {
					domain.setDomain_category("新闻");
				} else if ("EPaper".equals(domain.getDomain_category())) {
					domain.setDomain_category("电子报");
				} else if ("ResearchReport".equals(domain.getDomain_category())) {
					domain.setDomain_category("研报");
				} else if ("PublicNotice".equals(domain.getDomain_category())) {
					domain.setDomain_category("公告");
				} else if ("WeChat".equals(domain.getDomain_category())) {
					domain.setDomain_category("微信");
				} else if ("Weibo".equals(domain.getDomain_category())) {
					domain.setDomain_category("微博");
				} else if ("BBS".equals(domain.getDomain_category())) {
					domain.setDomain_category("论坛");
				} else if ("BLOG".equals(domain.getDomain_category())) {
					domain.setDomain_category("博客");
				} else if ("Live".equals(domain.getDomain_category())) {
					domain.setDomain_category("视频");
				} else {
					domain.setDomain_category("未知");
				}
				if (domain.getIs_delete()==0) {
					domain.setIs_deletes("停用");
				} else if (domain.getIs_delete()==1) {
					domain.setIs_deletes("启用");
				} else {
					domain.setIs_deletes("未知");
				}
			}
		}
		return dlist;
	}
	
	//导入
	@Override
	public void analyzeExcelData(File file,AnalyzeResult<Domain> result)throws Exception {
		List<Domain> list = new ArrayList<>();
		//解析文件
		Workbook work = Workbook.getWorkbook(file);
		//获取第一个工作表
		Sheet sheet = work.getSheet(0);
		int cols = 0;
		int rows = 0;
		//判断工作表获取是否正常
		if (CommonUtils.isObjectNotNull(sheet)) {
			//得到列数量
			cols = sheet.getColumns();
			//得到行数量
			rows = sheet.getRows();
			if (cols <= 1 || rows <= 1) {
				result.setResult(false, "未检测到数据", new ArrayList<Domain>());
			} else if (rows >= 9999999) {
				//行数大于上限，禁止导入
				result.setResult(false, "导入数量过多，请拆分数据分多次导入" + rows, new ArrayList<Domain>());
			}
		} else {
			//可能没有sheet（0）,也可能是其他愿意
			result.setResult(false, "Excel工作表格式错误", new ArrayList<Domain>());
		}
		if(!result.isSuccess()) {
			//数据不合法，直接返回
			return;
		}
		  // 若获取正常，进行下面的判断。不正常则跳过下面所有对于工作表的操作，并返回错误信息
		for (int i = 1; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				String domain_category = sheet.getCell(j++, i).getContents().trim();
				String domain_domain = sheet.getCell(j++, i).getContents().trim();
				String domain_name = sheet.getCell(j++, i).getContents().trim();
						
				if (!StringUtils.isBlank(domain_category)) {
					if ("新闻".equals(domain_category) || "News".equals(domain_category)) {
						domain_category = "News";
					} else if ("电子报".equals(domain_category) || "EPaper".equals(domain_category)) {
						domain_category = "EPaper";
					} else if ("研报".equals(domain_category) || "ResearchReport".equals(domain_category)) {
						domain_category = "ResearchReport";
					}else if ("公告".equals(domain_category) || "PublicNotice".equals(domain_category)){
						domain_category = "PublicNotice";
					} else if ("微信".equals(domain_category) || "WeChat".equals(domain_category)) {
						domain_category = "WeChat";
					} else if ("微博".equals(domain_category) || "Weibo".equals(domain_category)) {
						domain_category = "Weibo";
					} else if ("论坛".equals(domain_category) || "BBS".equals(domain_category)) {
						domain_category = "BBS";
					} else if ("博客".equals(domain_category) || "BLOG".equals(domain_category)) {
						domain_category = "BLOG";
					} else if ("视频".equals(domain_category) || "Live".equals(domain_category)) {
						domain_category = "Live";
					}
				} else {
					result.setResult(false, "第" + (i+1) + "行，格式错误", new ArrayList<Domain>());
				}
				if (domain_domain.length() < 0 || domain_domain.length() > 100) {
					result.setResult(false, "第" + (i+1) + "行，格式错误", new ArrayList<Domain>());
				}
				if (StringUtils.isBlank(domain_domain)) {
					result.setResult(false, "第" + (i+1) + "行，格式错误", new ArrayList<Domain>());
				}
				if (domain_name.length() < 0 || domain_name.length() > 100) {
					result.setResult(false, "第" + (i+1) + "行，格式错误", new ArrayList<Domain>());
				}
				if (StringUtils.isBlank(domain_name)) {
					result.setResult(false, "第" + (i+1) + "行，格式错误", new ArrayList<Domain>());
				}
				//如以上判断通过，则添加
				 if (result.isSuccess()) {
	                Domain domain = new Domain(null, domain_category,domain_domain,domain_name);
	                list.add(domain);
	             } else {
	                    // 有一个不符合，直接返回
	                return;
	             }
			}
		}
		 result.setResult(true, null, list);
	}
/*	 @Override
	 public List<Integer> insertFromExcel(List<Domain> domains) {
	        // 保存错误的行数List
	        List<Integer> errorIndexList = new ArrayList<Integer>();
	        // 任务List,为了提交任务后获取执行结果.
	        List<FutureTask<Integer>> taskList = new ArrayList<>();
	        for (int i = 0; i < domains.size(); i++) {
	            FutureTask<Integer> futureTask = new FutureTask<Integer>(new DomainExcelTask(domains.get(i), i + 2));
	            taskList.add(futureTask);
	           // taskExecutor.execute(futureTask);
	        }
	        // 遍历任务获取执行结果
	        for (FutureTask<Integer> task : taskList) {
	            try {
	                // 阻塞等待执行结果，知道执行完毕，设置超时时间20S
	                Integer result = task.get(20, TimeUnit.SECONDS);
	                if (result != null) {
	                    errorIndexList.add(result);
	                }
	            } catch (Exception e) {
	                task.cancel(true);
	            } finally {
	            }
	        }
	        return errorIndexList;
	    }

	    class DomainExcelTask implements Callable<Integer>, Serializable {
	        private static final long serialVersionUID = 1L;
	        private Domain domain;
	        private int num;

	        public DomainExcelTask(Domain domain, int num) {
	            this.domain = domain;
	            this.num = num;
	        }

	        @Override
	        public Integer call() {
	            // 插入站点并通过回调方法传回返回值
	            if (insert(domain)>0) {
	                return null;
	            }
	            return num;
	        }
	    }*/

	

}
